package com.yuzi.service.systemSer;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Record;
import com.yuzi.common.Constant;
import com.yuzi.model.systemMo.SysMenu;
import com.yuzi.model.systemMo.SysRoleMenu;
import com.yuzi.service.BaseSer.BaseService;
import com.yuzi.utils.DataUtils;
import org.apache.commons.lang3.StringUtils;

import java.sql.SQLException;
import java.util.*;

public class MenuService extends BaseService {

    private SysMenu sysMenuDao;

    private SysRoleMenu sysRoleMenuDao;
    /**
     * 初始化所有菜单
     * @param username
     * @return
     */
    public List<SysMenu> initMenu(String username){
        //根据用户查询父级菜单
        List<SysMenu> allSysMenu = sysMenuDao.findAllMenuByUser(username);
        //将菜单转成ZTree格式
        return toZTree(allSysMenu);
    }

    public List<Record> findAllMenu(Integer roleId){
        List<Record> allSysMenu = sysMenuDao.findAllAuthMenuByRoleId(roleId);
        List<Record> parentRecord = new ArrayList<>();
        List<Record> childRecord = null;

        Iterator<Record> iterator = allSysMenu.iterator();

        while (iterator.hasNext()){
            Record iRecord = iterator.next();
            if(iRecord.getInt("pid") == 0){
                parentRecord.add(iRecord);
                iterator.remove();
            }
        }
        iterator = allSysMenu.iterator();//重新回到起点
        for (Record record:parentRecord){
            childRecord = new ArrayList<>();
            while (iterator.hasNext()){
                Record iRecord = iterator.next();
                if (parentRecord.contains(iRecord)){
                    iterator.remove();
                    continue;
                }
                if(record.getInt("id") == iRecord.getInt("pid")){
                    childRecord.add(iRecord);
                    iterator.remove();
                }
            }
            record.set("child",childRecord);//record中可以添加新子节点，但是在model中就不可以
            iterator = allSysMenu.iterator();//重新回到起点
        }


        //allSysMenu = toZTree(allSysMenu);
        //记住这里的用法
        /*for (SysMenu sysMenu:allSysMenu){
            if (sysMenu.getChildren() == null){
                continue;
            }
            sysMenu.put("child",sysMenu.getChildren());
            sysMenu.setChildren(null);
        }*/
        //return allSysMenu;
        return parentRecord;
    }

    public List<SysMenu> toZTree(List<SysMenu> allSysMenu){
        SysMenu rootMenu = null;
        //找到root目录
        for (SysMenu sp:allSysMenu){
            if (-1 == sp.getInt("pid")){
                rootMenu = sp;
                break;
            }
        }
        if (rootMenu == null) return null;
        // 先找到所有的一级菜单
        List<SysMenu> ParentMenuList = getParentMenu(rootMenu,allSysMenu);

        for (SysMenu sysMenu:ParentMenuList){
            sysMenu.setChildren(getChild(sysMenu.getInt("id"),allSysMenu));
        }
        return ParentMenuList;
    }

    //获取一级父级菜单
    private List<SysMenu> getParentMenu(SysMenu sysMenu,List<SysMenu> allSysMenu){
        List<SysMenu> sysMenuList = new ArrayList<>();
        Iterator<SysMenu> iterator = allSysMenu.iterator();
        while (iterator.hasNext()){
            SysMenu iSysMenu = iterator.next();
            if(sysMenu.getInt("id") == iSysMenu.getInt("pid")){
                sysMenuList.add(iSysMenu);
                iterator.remove();
            }
        }
        sysMenu.setChildren(sysMenuList);
        return sysMenuList;
    }

    private List<SysMenu> getChild(int id ,List<SysMenu> allSysMenu){
        //子菜单
        List<SysMenu> childMenu = new ArrayList<>();
        Iterator<SysMenu> allSysMenuIterator = allSysMenu.iterator();

        while (allSysMenuIterator.hasNext()){
            SysMenu iSysMenu = allSysMenuIterator.next();
            // 遍历所有节点，将父菜单id与传过来的id比较
            if (id == iSysMenu.getInt("pid")){
                childMenu.add(iSysMenu);
                allSysMenuIterator.remove();
            }
        }

        // 把子菜单的子菜单再循环一遍
        Iterator<SysMenu> childMenuIterator = childMenu.iterator();
        while (childMenuIterator.hasNext()){
            SysMenu ichildSysMenu = childMenuIterator.next();
            // 没有url子菜单还有子菜单
            if (StringUtils.isBlank(ichildSysMenu.getStr("url"))){
                ichildSysMenu.setChildren(getChild(ichildSysMenu.getInt("id"),allSysMenu));
            }
        }
        //递归退出条件
        if (childMenu.size() == 0){
            return null;
        }
        return childMenu;
    }

    //获取Root目录和一级木目录
    public List<SysMenu> getRootAndParentMenu(){
        return sysMenuDao.getRootAndParentMenu();
    }

    public List<SysMenu> getChildMenu(int pid){
        return sysMenuDao.getChildMenu(pid);
    }

    public Map<String, String> addMenu(SysMenu sysMenu){

        final Map<String ,String> map = new HashMap<>();
        boolean res = Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {
                //添加菜单
                int id =  sysMenuDao.addMenu(sysMenu);

                if (id >0){
                    //将权限添加给超级管理员（id ：1）
                    boolean flag = sysRoleMenuDao.addSysRoleMenu(1,id);
                    if (flag) {
                        map.put("flag","true");
                        map.put("res", "菜单添加成功");
                        return true;
                    }else{
                        map.put("flag","false");
                        map.put("res","添加失败，该权限已存在");
                        return false;
                    }
                }else {
                    map.put("flag","false");
                    map.put("res","菜单添加失败");
                    return false;
                }
            }
        });
        return map;
    }

    public SysMenu findSysMenuById(Integer id){
        return sysMenuDao.findById(id);
    }

    public boolean updateMenu(SysMenu sysMenu){
        return sysMenuDao.updateMenu(sysMenu);
    }

    public Map<String ,String> deleteSysMenu(int id){
        final Map<String ,String> map = new HashMap<>();

        boolean isExit = DataUtils.isExitInteger(Constant.SysConfig.sys_menu_id,id);
        if (isExit){
            map.put("flag","false");
            map.put("msg","禁止删除该菜单");
            return map;
        }

        List<SysMenu> sysMenuChildList = getChildMenu(id);
        if (sysMenuChildList != null && sysMenuChildList.size() > 0){
            map.put("flag","false");
            map.put("msg","请先删除子菜单");
            return map;
        }
        boolean res = Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {

                boolean isDelete = sysMenuDao.deleteById(id);
                if (isDelete){
                    //将权限表中的关联关系删掉（sys_role_menu）,通过menu_id
                    sysRoleMenuDao.deleteSysRoleMenuByMenuId(id);
                    map.put("flag","true");
                    map.put("msg","删除成功");
                    return true;
                }else{
                    map.put("flag","false");
                    map.put("msg","删除失败");
                    return false;
                }
            }
        });
        return map;
    }

    public List<SysMenu> findAllMenuByNoDeal(){
        List<SysMenu> sysMenuList = sysMenuDao.findAllMenuByNoDeal();
        return sysMenuList;
    }

    public List<SysMenu> findAllMenuByRoleNoDeal(Integer roleId){
        List<SysMenu> sysMenuList = sysMenuDao.findAllMenuByRoleNoDeal(roleId);
        return sysMenuList;
    }


    public boolean updateSysUserStatusById(int id,String ishidden){
        SysMenu sysMenu = findSysMenuById(id);
        sysMenu.set("ishidden",ishidden);
        return sysMenu.update();
    }
}
